package com.jiajia.server.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jiajia.server.pojo.Employee;
import com.jiajia.server.pojo.MailConstants;
import com.jiajia.server.pojo.MailLog;
import com.jiajia.server.service.IEmployeeService;
import com.jiajia.server.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author ZSJia
 * @date 2021/8/20 020 - 14:51
 */
@Component
public class MailTask {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private IMailLogService mailLogService;
    @Autowired
    private IEmployeeService employeeService;


    @Scheduled(cron = "0/10 * * *  * ?")
    public  void mailTask(){
        //首先查询状态为正在发送中的消息而且重试时间小于当前时间
        List<MailLog> mailLogs = mailLogService.list(new QueryWrapper<MailLog>()
                .eq("status", 0).
                        lt("tryTime", LocalDateTime.now()));
        //如果重试次数大于3次不在重试设置为发送失败状态
        mailLogs.forEach(mailLog->{
            if (mailLog.getCount()>=3){
                mailLogService.update(new UpdateWrapper<MailLog>()
                        .set("status",2)
                        .eq("msgId",mailLog.getMsgId()));
            }

            //更新重试次数，更新时间，重试时间
            mailLogService.update(new UpdateWrapper<MailLog>().set("count",mailLog.getCount()+1)
                    .set("updateTime",LocalDateTime.now())
                    .set("tryTime",LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT))
                    .eq("msgId",mailLog.getMsgId()));

            //获取需要发送的消息信息
            Employee employee = employeeService.exportListEmp(mailLog.getEId()).get(0);
            //发送消息
            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME
                                                                    ,MailConstants.MAIL_ROUTING_KEY_NAME
                                                                    ,employee,new CorrelationData(mailLog.getMsgId()));

        });


    }


}
